package com.hele.sts.action;

import com.hele.sts.pub.Captcha;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

@Controller
public class CaptchaController implements Action {

    //图片流
    private ByteArrayInputStream inputStream;

    String action;
//    @RequestMapping(value = "/captcha")
//    @ResponseBody
    public void imagecode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        OutputStream os = response.getOutputStream();
        //返回验证码和图片的map
        Map<String,Object> map = Captcha.getImageCode(86, 37, os);
        String simpleCaptcha = "simpleCaptcha";
        request.getSession().setAttribute(simpleCaptcha, map.get("strEnsure").toString().toLowerCase());
        request.getSession().setAttribute("codeTime",System.currentTimeMillis());
        try {
            ImageIO.write((BufferedImage) map.get("image"), "jpg", os);
        } catch (IOException e) {
            //return "";
        }   finally {
            if (os != null) {
                os.flush();
                os.close();
            }
        }
        //return null;
    }

    @Override
    public String execute() throws Exception {

        ActionContext ctx = ActionContext.getContext();
        Map session = ctx.getSession();

        if("showCaptcha".equals(action)){
            //imagecode();
        }
        return null;
    }



    public String getAction() {
        return action;
    }

    public void setAction(String action) {
        this.action = action;
    }

    public ByteArrayInputStream getInputStream() {
        return inputStream;
    }
}
